package iziswing.composant;

import iziswing.SwingXml;

import java.awt.Container;
import java.awt.Point;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;

import javax.swing.JComponent;

import metier.ContexteComposant;

import org.apache.log4j.Logger;

import exception.ComposantException;
import exception.DisplayException;
import exception.SwingXmlException;

@SuppressWarnings("serial")
public class JRadioButton extends javax.swing.JRadioButton implements
		FocusListener {

	private static Logger mLogger = Logger
			.getLogger(JTextField.class.getName());

	private Container mFenetre;
	private ContexteComposant mContexte;

	public JRadioButton(Container aFenetre, ContexteComposant aContexte)
			throws ComposantException {
		super(aContexte.getTitre());
		mFenetre = aFenetre;
		mContexte = aContexte;
		Point lPoint = ComposantTools.getSize(mContexte);
		setBounds(mContexte.getX(),mContexte.getY(),lPoint.y,lPoint.x);
		addFocusListener(this);
		refresh();
		mFenetre.add(this);
	}

	public void refresh() throws ComposantException {
		if (mFenetre != null) {
			Object lObject;
			try {
				lObject = SwingXml.getValue(mFenetre, mContexte.getBean());
				boolean lNewState = (Boolean) lObject;
				setSelected(lNewState);
			} catch (SwingXmlException e) {
				throw new ComposantException(e);
			}
		}
	}

	public void sauvegarder() throws DisplayException {
		if (mFenetre != null) {
			boolean lNewState = isSelected();
			mLogger.debug("Set valeur :" + lNewState);
			try {
				SwingXml.setValue(mFenetre, mContexte.getBean(), lNewState);
			} catch (SwingXmlException e) {
				throw new DisplayException(e);
			}
		}
	}

	@Override
	public void focusGained(FocusEvent aArg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void focusLost(FocusEvent aArg0) {
		// TODO Auto-generated method stub
		mLogger.debug("Debut de la sauvegarde du Contenu du champ");
		try {
			sauvegarder();
		} catch (DisplayException e) {
			e.display();
		}
		mLogger.debug("Fin de la sauvegarde");
	}

	@SuppressWarnings("unchecked")
	public static Object newInstance(Container aFenetre, ContexteComposant aContexte,
			Object aComposantOut) throws ComposantException {
		try {
			Class<JComponent> lComposant = (Class<JComponent>) Class
					.forName(aContexte.getModeleClasse().getClasse());
			if (lComposant.equals(JRadioButton.class)) {
				aComposantOut = new JRadioButton(aFenetre,aContexte);
			}
		} catch (ClassNotFoundException e) {
			mLogger.debug(e);
		}
		return aComposantOut;
	}
}
